<?php

namespace App\Http\Controllers\Tools;

use App\Http\Common\HttpRequest;
use App\Http\Common\MyUtils;
use App\Http\Controllers\Controller;
use App\Models\Developer\DeveloperPackage;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Session;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Facades\JWTFactory;

/**
 * 权限控制器
 * Class MailController
 * @package App\Http\Controllers\Tools
 */
class AccessController extends Controller
{
    /**
     * 生成唯一的token
     * @param $request
     * @return string
     */
    public function getToken(Request $request){
        $bucket_id = $request->bucket_id;
        $bucket_secret = $request->bucket_secret;
        $count = DeveloperPackage::where(['unique_id'=>$bucket_id,'unique_key'=>$bucket_secret])->get()->count();
        if ($count){
            // 得到今天access_token接口请求的次数
            $getTimes = MyUtils::getInstance()->getTodayRequestTimes('access_token',"$bucket_id.,.$bucket_secret");
            if ($getTimes<2000) {
                $expires_in = 7200;
                $code = $bucket_id.','.$bucket_secret;
                $accessToken = MyUtils::encodeNew($code, env('APP_KEY'), $expires_in);
                $data['access_token'] = $accessToken;
                $data['create_time'] = time();
                $data['expires_in'] = $expires_in;
                return MyUtils::dealFD($data,1);
            }else{
                return MyUtils::dealFD("您今天获取的次数已经超过 2000 次",1);
            }
        }else{
            return MyUtils::dealFD("获取accessToken失败，请该秘钥的套件不存在，请进套件查看秘钥",-1);
        }
    }
    /**
     * 解析唯一的token
     * @param $request
     * @return string
     */
    public function parseToken(Request $request){
        $res = MyUtils::getInstance()->parseToken($request->access_token);
        return $res;
    }

    /**
     * 生成二维码图片
     * @param Request $request
     * @return ResponseFactory|Response
     * 接收方式 post
     * 接收参数 @param1 请求的url
     */
    public function getQrCode(Request $request){
        return response(HttpRequest::getInstance()->get($request->url),200,['Content-Type'=>'image/png']);
    }

    /**
     * 前端保存session的接口
     * 接收方式 post
     * 接收参数 @param1
     * @param Request $request 请求的数据
     * @return int
     */
    public function saveSession(Request $request){
        foreach ($request->all() as $k=>$v){
            if ($v && $k!='token'){
                Session::put($k, $v);
            }
        }
        return MyUtils::dealFD('保存session成功',1);
    }

}
